package grape.attend.rest.user.mvc;

import com.baomidou.mybatisplus.core.metadata.IPage;
import grape.attend.rest.user.form.MyLeaveApplicationListPageForm;
import grape.attend.rest.user.mapper.UserLeaveWebMapper;
import grape.attend.service.user.api.IUserLeaveService;
import grape.base.rest.client.dict.DictClient;
import grape.base.service.dict.po.Dict;
import grape.common.exception.ExceptionTools;
import grape.common.exception.runtime.InvalidParamsException;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
import javax.validation.Valid;
import grape.attend.rest.user.form.UserLeaveApplicationCreateForm;
import grape.attend.rest.user.form.UserLeaveApplicationUpdateForm;
import grape.attend.rest.user.form.UserLeaveApplicationListPageForm;
import grape.attend.rest.user.vo.UserLeaveApplicationVo;
import grape.attend.rest.user.mapper.UserLeaveApplicationWebMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestController;
import grape.common.rest.mvc.BaseController;
import grape.attend.service.user.po.UserLeaveApplication;
import grape.attend.service.user.api.IUserLeaveApplicationService;
import springfox.documentation.annotations.ApiIgnore;

import java.util.List;
/**
 * <p>
 * 用户请/补假单表 前端控制器
 * </p>
 *
 * @author yangwei
 * @since 2020-05-29
 */
@RestController
@RequestMapping("/attend/userleaveapplication")
@Api(tags = "用户请/补假单表相关接口")
public class UserLeaveApplicationController extends BaseController<UserLeaveApplicationVo, UserLeaveApplication> {

    @Autowired
    private UserLeaveApplicationWebMapper currentWebMapper;
    @Autowired
    private IUserLeaveApplicationService currentService;
    @Autowired
    private UserLeaveWebMapper userLeaveWebMapper;
    @Autowired
    private IUserLeaveService iUserLeaveService;

    @Autowired
    private DictClient dictClient;


     @ApiOperation("添加用户请/补假单")
     @PreAuthorize("hasAuthority('userleaveapplication:create')")
     @PostMapping
     @ResponseStatus(HttpStatus.CREATED)
     public UserLeaveApplicationVo create(@RequestBody @Valid UserLeaveApplicationCreateForm cf,@ApiIgnore String loginUserId) {
         UserLeaveApplication po = currentWebMapper.formToPo(cf);
         po.setUserId(loginUserId);
         UserLeaveApplication userLeaveApplication = currentService.addUserLeaveApplication(po, userLeaveWebMapper.formsToPos(cf.getUserLeaves()), cf.getIsSubmitApprove());
         return super.returnCreate(userLeaveApplication);
     }

     @ApiOperation("根据ID查询用户请/补假单")
     @PreAuthorize("hasAuthority('userleaveapplication:single:queryById')")
     @GetMapping("/{id}")
     @ResponseStatus(HttpStatus.OK)
     public UserLeaveApplicationVo queryById(@PathVariable String id) {
         return super.queryById(id);
     }

     @ApiOperation("删除用户请/补假单")
     @PreAuthorize("hasAuthority('userleaveapplication:single:deleteById')")
     @DeleteMapping("/{id}")
     @ResponseStatus(HttpStatus.NO_CONTENT)
     public boolean deleteById(@PathVariable String id) {
         // 可以删除未提交的
         UserLeaveApplication leaveApplication = currentService.getById(id);
         if (leaveApplication == null) {
             throw ExceptionTools.dataNotExistRE("数据不存在，请刷新后再试");
         }else {
             Dict dict = dictClient.getDictByCode(UserLeaveApplication.DictApproveStatus.user_leave_application_approve_unsubmit.name());
             if (!isEqual(leaveApplication.getApproveStatusDictId(),dict.getId())) {
                 throw new InvalidParamsException("不能删除已提交的假期申请");
             }
         }
         return super.deleteById(id);
     }

     @ApiOperation("更新用户请/补假单")
     @PreAuthorize("hasAuthority('userleaveapplication:updateById')")
     @PutMapping("/{id}")
     @ResponseStatus(HttpStatus.CREATED)
     public UserLeaveApplicationVo update(@PathVariable String id,@RequestBody @Valid UserLeaveApplicationUpdateForm uf,@ApiIgnore String loginUserId) {

         // 可以删除未提交的
         UserLeaveApplication leaveApplication = currentService.getById(id);
         if (leaveApplication == null) {
             throw ExceptionTools.dataNotExistRE("数据不存在，请刷新后再试");
         }else {
             Dict dict = dictClient.getDictByCode(UserLeaveApplication.DictApproveStatus.user_leave_application_approve_unsubmit.name());
             if (!isEqual(leaveApplication.getApproveStatusDictId(),dict.getId())) {
                 throw new InvalidParamsException("不能修改已提交的假期申请");
             }
         }

         UserLeaveApplication po = currentWebMapper.formToPo(uf);
         po.setUserId(loginUserId);
         po.setId(id);
         UserLeaveApplication userLeaveApplication = currentService.updateUserLeaveApplication(po, userLeaveWebMapper.formsToPos(uf.getUserLeaves()), uf.getIsSubmitApprove());
         if (userLeaveApplication == null) {
             throw ExceptionTools.failRE("更新失败，请刷新数据后再试");
         }
         return transVo(currentWebMapper.poToVo(currentService.getById(userLeaveApplication.getId())));
     }

    @ApiOperation("分页查询用户请/补假单表")
    @PreAuthorize("hasAuthority('userleaveapplication:single:listPage')")
    @GetMapping("/listPage")
    @ResponseStatus(HttpStatus.OK)
    public IPage<UserLeaveApplicationVo> listPage(UserLeaveApplicationListPageForm listPageForm) {
         UserLeaveApplication po = currentWebMapper.formToPo(listPageForm);
         return super.listPage(po,listPageForm);
     }

    /**
     * 我的假期申请
     * @param listPageForm
     * @return
     */
    @ApiOperation("分页查询当前用户请/补假单")
    @PreAuthorize("hasAuthority('userleaveapplication:single:myListPage')")
    @GetMapping("/myListPage")
    @ResponseStatus(HttpStatus.OK)
    public IPage<UserLeaveApplicationVo> myListPage(MyLeaveApplicationListPageForm listPageForm, @ApiIgnore String loginUserId) {
        UserLeaveApplication po = currentWebMapper.formToPo(listPageForm);
        po.setUserId(loginUserId);
        return super.listPage(po,listPageForm);
    }

    @Override
    public UserLeaveApplicationVo transVo(UserLeaveApplicationVo userLeaveApplicationVo) {
        userLeaveApplicationVo.setUserLeaves(userLeaveWebMapper.posToVos(iUserLeaveService.getByUserLeaveApplicationId(userLeaveApplicationVo.getId())));
        return super.transVo(userLeaveApplicationVo);
    }
}
